package test.ground.netty.netty.my;

import java.nio.charset.Charset;

/**
 * @Description
 * @Author shaopeng
 * @Date 2021/11/17
 * @Version 1.0
 */
public class Message {
    public static final Charset charset = Charset.forName("utf-8");

    private byte type;//消息类型 1:心跳包  2:业务
    private long requestId; //请求id
    private int length;
    private String body;

    /**
     * 心跳
     */
    public Message(){
        this.type = 1;
        this.requestId = System.nanoTime();
        this.length = "ping".getBytes(charset).length;
        this.body = "ping";
    }


    /**
     * 业务
     * @param body
     */
    public Message(String body) {
        this.type = 2;
        this.requestId = System.nanoTime();
        this.length = body.getBytes(charset).length;
        this.body = body;
    }

    public Message(byte type, long requestId, byte[] data) {
        this.type = type;
        this.requestId = requestId;
        this.length = data.length;
        this.body = new String(data, charset);
    }

    /**
     * 是不是心跳
     * @return
     */
    public boolean isPing(){
        return type == 1;
    }

    /**
     * 是不是业务
     * @return
     */
    public boolean isBiz(){
        return type == 2;
    }

    public byte getType() {
        return type;
    }

    public void setType(byte type) {
        this.type = type;
    }

    public long getRequestId() {
        return requestId;
    }

    public void setRequestId(long requestId) {
        this.requestId = requestId;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Charset getCharset() {
        return charset;
    }

    @Override
    public String toString() {
        return "Message{" +
                "charset=" + charset +
                ", type=" + type +
                ", requestId=" + requestId +
                ", length=" + length +
                ", body='" + body + '\'' +
                '}';
    }
}